package com.lemon.cloud.oauth.support.core;

import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.oauth.handler.FormAuthenticationFailureHandler;
import com.lemon.cloud.oauth.handler.SsoLogoutSuccessHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;

import static com.lemon.cloud.comm.constants.OAuth2Constant.*;

/**
 * 基于授权码模式 统一认证登录 spring security & sas 都可以使用 所以抽取成 HttpConfigurer
 *
 * @author HuangDS
 */
public final class FormIdentityLoginConfig extends AbstractHttpConfigurer<FormIdentityLoginConfig, HttpSecurity> {

    private String applicationName;

    public FormIdentityLoginConfig(String applicationName) {
        this.applicationName = applicationName;
    }

    @Override
    public void init(HttpSecurity http) throws Exception {
        http.formLogin(formLogin -> {
            formLogin.loginPage(StrUtil.C_SLASH + applicationName + CUSTOM_CONSENT_LOGIN_PAGE);
            formLogin.loginProcessingUrl(StrUtil.C_SLASH + applicationName + CUSTOM_CONSENT_LOGIN_URL);
            formLogin.failureHandler(new FormAuthenticationFailureHandler(applicationName));
        }).logout() // SSO登出成功处理
                .logoutSuccessHandler(new SsoLogoutSuccessHandler()).deleteCookies(JSESSIONID)
                .invalidateHttpSession(true).and().csrf().disable();
    }
}
